package com.joinlabs.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.joinlabs.entity.User;
import com.joinlabs.service.IUserService;
import com.joinlabs.util.MD5Utils;
import com.joinlabs.util.SendCodeUtil;

@Controller
@RequestMapping("/user")
@SessionAttributes(names="user")
public class SetPassWordAction {
	@Resource
	private IUserService userService;
	@RequestMapping("/setpwd")
	public ModelAndView showsetpwd(){
		return new ModelAndView("/setpassword/setpassword");
	}
	
	//判断账号是否存在
	@RequestMapping("/checkph")
	@ResponseBody
	public String checkphone(User user){
		String userPhone = user.getUserPhone();
		user = userService.checkphone(userPhone);
		if(user != null){
			return "false";
		}
		return "true";
	}
	
	//修改密码功能
	@RequestMapping("/setpassword/*")
	public ModelAndView setpassword(User user,HttpServletRequest request, HttpServletResponse response){
		String ss = request.getServletPath();
		String userPhone = user.getUserPhone();
		String userPassword = user.getUserPassword();
		if("/user/setpassword/gainNote".equals(ss)){     //获取短信验证码的逻辑
			userPhone = user.getUserPhone();
			String code = request.getParameter("code");
			user.setUserPhone(userPhone);//手机号码
			String uphone = request.getParameter("uphone");
			String sendsm = SendCodeUtil.sendsms(uphone);
			System.out.println(sendsm);
			JSONObject jo = (JSONObject) JSONObject.parse(sendsm);
			String notecode = jo.getString("obj");
			System.out.println(notecode);
			request.getSession().setAttribute("notecode",notecode);
		}
		
		if("/user/setpassword/success".equals(ss)){
			String pwd = MD5Utils.MD5Encode(userPassword, "utf-8");//加密修改的密码
			userService.setpassword(userPhone, pwd);
			return new ModelAndView("/setpassword/setpasswordsuccess");
		}
		return null;	
	}
	
	//判断短信验证码是否正确
	@RequestMapping("/scode")
	@ResponseBody
	public String checkcode(HttpServletRequest request){
		String sendcode = request.getParameter("sendcode");
		String code = (String) request.getSession().getAttribute("notecode");
		if(code != null && sendcode.equals(code)){
			return "true";
		}
		return "false";
	}
}
